package com.yc.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yc.domain.UserBean;
import com.yc.mapper.UserMapper;
import com.yc.model.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zwei
 * @create 2024-09-26 15:01
 */
@Service
@Transactional    //事务控制
@Slf4j
public class UserBizImpl implements UserBiz, UserDetailsService {
    private UserMapper userMapper;
    @Autowired
    public void setResuserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    private PasswordEncoder passwordEncoder;
    @Autowired
    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<UserBean> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(UserBean::getUsername,username);      //where username="a"
        try {
            //这是一个userDetails对象
            UserBean resuser=userMapper.selectOne(wrapper);   //select*from resuser where username=? 这里要确保username是唯一的
            return resuser;
        }catch (Exception e){
            log.error("user is not find");
            return null;
        }
    }
    @Override
    public int regUser(UserVO userVO) {
        //判断用户是否存在
        QueryWrapper<UserBean> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",userVO.getUsername());
        List<UserBean> list=userMapper.selectList(queryWrapper);
        if (list!=null&&list.size()>0){
            throw new RuntimeException("用户名"+userVO.getUsername()+"已存在");
        }
        UserBean resuser=new UserBean();
        resuser.setUsername(userVO.getUsername());
        resuser.setPassword(passwordEncoder.encode(userVO.getPwd()));
        resuser.setEmail(userVO.getEmail());
        userMapper.insert(resuser);
        return resuser.getId();
    }


}
